package com.dzsw.netty.basic.time;
import com.google.common.base.Strings;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class TimeZoneConversion {
    public static void main(String[] args) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(formater.format(new Date(Long.valueOf("1721613498516"))));
        Date date = convertSystemTimeZone("1721613498516");
        System.out.println(formater.format(date));
    }

    public static void originalCode() {
        // 步骤1：获取当前时间戳
        long currentTimeMillis = System.currentTimeMillis();
        // 步骤2：创建Instant对象
        Instant instant = Instant.ofEpochMilli(currentTimeMillis);
        // 步骤3：创建ZonedDateTime对象，使用系统默认时区
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
        // 步骤4：转换为指定时区，这里以东京时区为例
//        ZoneId tokyoZoneId = ZoneId.of("Asia/Tokyo");
        ZoneId systemZoneId = ZoneId.systemDefault();
        ZonedDateTime tokyoDateTime = zonedDateTime.withZoneSameInstant(systemZoneId);
        // 步骤5：格式化日期时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z");
        String formattedDateTime = tokyoDateTime.format(formatter);
        // 输出结果
        System.out.println("System zone time = " + formattedDateTime);
    }

    /**
     * Convert date to system zone time
     * @param strDate
     * @return
     */
    public static Date getSystemZonedDate(String strDate) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
        LocalDateTime localDateTime = LocalDateTime.parse(strDate, dateTimeFormatter);
        ZonedDateTime utcZonedDateTime = ZonedDateTime.of(localDateTime, ZoneOffset.UTC);
        ZoneOffset localZoneOffset = OffsetDateTime.now().getOffset();
        return Date.from(utcZonedDateTime.withZoneSameInstant(localZoneOffset).toInstant());
    }

    public static Date convertSystemTimeZone(String timeMillis) {
        if (Strings.isNullOrEmpty(timeMillis)) {
            return null;
        }
        long currentTimeMillis = Long.valueOf(timeMillis);
        Instant instant = Instant.ofEpochMilli(currentTimeMillis);
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
        ZoneId systemZoneId = ZoneId.systemDefault();
        ZonedDateTime systemDateTime = zonedDateTime.withZoneSameInstant(systemZoneId);
        return Date.from(systemDateTime.toInstant());
    }
}